package geektime.io.netty.homework;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;

/**
 * 模拟服务端
 */
public class DemoServer {
    private static final int PORT = Integer.valueOf(System.getProperty("port", "12345"));

    public static void main(String[] args) {
        // 创建bossGroup和workerGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 创建serverBootstrap
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // serverBootstrap参数设置，包含eventGroup、IO通道类型、通道配置选项、handler和childHandler
            serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new DemoServerHandler());
                    }
                });
            System.out.println("Server start...");
            // serverBootstrap绑定端口并开始监听
            ChannelFuture channelFuture = serverBootstrap.bind(PORT).sync();
            // 自我阻塞直到通道关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
